package com.spc.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.spc.dao.CheckGroupDao;
import com.spc.dao.CheckItemDao;
import com.spc.entity.PageResult;
import com.spc.entity.QueryPageBean;
import com.spc.pojo.CheckGroup;
import com.spc.pojo.CheckItem;
import com.spc.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //调用checkGroupDao存储数据
        checkGroupDao.add(checkGroup);
        //获取自增产生的id
        Integer checkGroupId = checkGroup.getId();
        this.saveId(checkitemIds,checkGroupId);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //取出分页条件
        Integer currentPage = queryPageBean.getCurrentPage();//当前页码
        Integer pageSize = queryPageBean.getPageSize();//每页记录数
        String queryString = queryPageBean.getQueryString();//查询条件
        //调用dao完成分页查询，使用mybatis分页助手插件
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> page = checkGroupDao.findByCondition(queryString);
        long total = page.getTotal();
        List<CheckGroup> rows = page.getResult();
        PageResult pageResult = new PageResult(total, rows);

        return pageResult;
    }

    @Override
    public CheckGroup findById(Integer id) {
        CheckGroup checkGroup = checkGroupDao.findById(id);
        return checkGroup;
    }

    @Override
    public List<Integer> findIds(Integer id) {
        List<Integer> ids = checkGroupDao.findIds(id);
        return ids;
    }

    @Override
    public void edit(Integer[] ids, CheckGroup checkGroup) {
        //调用dao修改checkGroup
        checkGroupDao.editCheckGroup(checkGroup);
        //清理关联数据
        Integer checkGroupId = checkGroup.getId();
        checkGroupDao.deleteById(checkGroupId);
        //调用dao添加关联关系
        this.saveId(ids,checkGroupId);

    }

    //查询所有检查组
    @Override
    public List<CheckGroup> findAll() {
        List<CheckGroup> checkGroups = checkGroupDao.findAll();
        return checkGroups;
    }

    //建立检查组检查项关联关系
    public void saveId(Integer[] checkitemIds,int checkGroupId){
        if (checkitemIds != null && checkitemIds.length> 0){
            Map<String,Object> map = new HashMap<>();
            map.put("checkgroupId", checkGroupId);
            map.put("checkitemId", checkitemIds);
            checkGroupDao.saveId(map);
        }

    }

}
